package club.baimahu.pencil.domain.entity;

import club.baimahu.pencil.domain.entity.account.CashAccount;
import club.baimahu.pencil.domain.entity.account.SimpleAccountManager;
import club.baimahu.pencil.domain.session.Supermarket;
import club.baimahu.pencil.exception.BuyException;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;


@Data
public class CommonBuyer extends SimpleAccountManager implements Buyer{

    Logger logger = LoggerFactory.getLogger(CommonBuyer.class);

    Supermarket supermarket;

    String name;

    public CommonBuyer(String name){
        this.name = name;
        super.setAccountManagerName(name);
    }

    public void startShopping(Supermarket supermarket){
        this.supermarket = supermarket;
    }

    public void leave(Supermarket supermarket){
        this.supermarket = null;
    }

    public void addCacheAccount(String accountName ,BigDecimal balance){
        this.addAccount(new CashAccount(accountName,balance));
    }


    @Override
    public boolean buy(String goodsNo,Seller seller) {
        if(seller == null){
            throw new BuyException("seller is null");
        }
        if(!seller.hasGoods(goodsNo)){
            throw new BuyException("goods :  " + goodsNo + " has no left");
        }
        Goods goods = seller.getGoods(goodsNo);
        if(!this.canAfford(goods.getSellPrice())){
            throw new BuyException("buyer account has not enough money");
        }
        // todo 缺少事务支持
        boolean success = seller.sell(goods,this);
        if(success){
            this.pay(goods.getSellPrice(),seller);
            logger.info("{}购买商品‘{}’成功",this.name,goodsNo);
        }
        return success;
    }


}
